package com.fay.designPattern.principles.dry;

import org.apache.commons.lang.StringUtils;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/3/3 14:14
 * @Version 1.0
 */
public class UserAuthenticator {
    public void authenticate(String username, String password) {
        if (!isValidUsername(username)) {
            // throw InvalidUsernameException
        }
        if (!isValidPassword(password)) {
            // throw InvalidUsernameException
        }
        //...
    }



    private boolean isValidUsername(String username) {
        // check not null, not empty
        if (StringUtils.isBlank(username)) {
            return false;
        }
        // check length: 4-64
        int length = username.length();
        if (length < 4 || length > 64) {
            return false;
        }
        // contains only low case characters
        if (!StringUtils.isAllLowerCase(username)) {
            return false;
        }
        // contains only a-z, 0-9, dot
        for (int i = 0; i < length; ++i) {
            char c = username.charAt(i) ;
            if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.')) {
                return false;
            }
        }
        return true;
    }

    private boolean isValidPassword(String password) {
        // check not null, not empty
        if (StringUtils.isBlank(password)) {
            return false;
        }
        // check length: 4-64
        int length = password.length();
        if (length < 4 || length > 64) {
            return false;
        }
        // contains only low case characters
        if (!StringUtils.isAllLowerCase(password)) {
            return false;
        }
        // contains only a-z, 0-9, dot
        for (int i = 0; i < length; ++i) {
            char c = password.charAt(i) ;
            if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.')) {
                return false;
            }
        }
        return true;
    }

}
